 //
//  UserAccount.swift
//  01-WeiBo
//
//  Created by 李晓东 on 17/6/30.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {

    var access_token :String?
    var expires_in : TimeInterval = 0{
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    var remind_in :String?
    var uid :String?
    
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    var expiresDate:Date?
    
    init(params:[String: Any]) {
        super.init()
        setValuesForKeys(params)
        
    }
    
    func saveUserAccount(){
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
        path = (path as NSString).appendingPathComponent("userInfo.plist")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    // 归档 把对象序列化归档到磁盘上
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        let key = ["access_token", "expires_in", "uid", "expiresDate"]
        return dictionaryWithValues(forKeys: key).description
    }
    
}
